// pages/plays/plays.js
let {getMusicUrl} = require(`../../api/player`)
Page({
  data:{
      // 定义当前音乐播放状态
      playSate:false,
      // 定义播放模式 0表示随机播放 1表示顺序播放 2表示单曲循环
      playMode:0,
      // 是否展示播放列表
      playListShow:false,
      playList:[],
      // 音乐播放索引
      playIndex:0,
      musicMsg:null,
      //音乐播总市场
      duration:"00:00",
      //当前播放进度
      currentTime:"00:00",
      percent:0
  },
  onTabItemTap(item){
    let playList = wx.getStorageSync('playList');
    console.log(playList)
    console.log(item)
    if(playList==''){
      wx.showToast({
        title: '暂无播放歌曲',
        icon:"none",
        success(){
          setTimeout(() => {
               wx.switchTab({
              url: '/pages/index/index',
            })
          }, 2000);
         
        }
      })
      return
  }
  },
  //页面路径变有且只会执行一次
  onLoad(options){
    console.log(options)
    if(options.isRandom==1){
       let playList = wx.getStorageSync('playList');
       this.setData({
           playList:playList,
       },()=>{
           this.randomMusic();
       })
       return;
    }
   // 获取播放索引
   let playIndex = options.index;
   if(playIndex==undefined){
       playIndex =0;
   }
   // 获取本地存储的播放列表
   let playList = wx.getStorageSync('playList');
   if(playList==''){
       return
   }
   this.setData({
       playList:playList,
       playIndex:playIndex
   },()=>{
       this.getMusicMsg();
   })
},
  // 子组件改变播放状态
  changeState(){
    if(this.data.playSate){
      //暂停播放
      this.BackgroundAudioManager.pause();
    }else{
      //开始播放
      this.BackgroundAudioManager.play();
    }
      this.setData({
          playSate:!this.data.playSate
      })
  },
  // 子组件改变播放模式
  changePlayMode(){
    console.log(1111111111)
    
    this.data.playMode++;
    if(this.data.playMode>2){
        this.data.playMode = 0;
    }
    this.setData({
        playMode:this.data.playMode
    })
},
  showPlayList(){
      this.setData({
          playListShow:true
      })
  },
  close(){
      this.setData({
          playListShow:false
      })
  },
  // 获取将要播放音乐的信息
  getMusicMsg(){
    this.setData({
      duration:"00:00",
      currentTime:"00:00",
      percent:0
    })
      let musicMsg = this.data.playList[this.data.playIndex];
      let ar = [];
      // 处理歌手
      musicMsg.ar.forEach(item=>{
          ar.push(item.name)
      })
      // 处理所用到歌曲信息
      musicMsg = {
          name:musicMsg.name,
          picUrl:musicMsg.al.picUrl,
          ar:ar.join("、"),
          id:musicMsg.id
      }
      this.setData({
          musicMsg:musicMsg
      },()=>{
          this.getPlayUrl();
      })
  },
  // 播放列表切歌
  playMusic(e){
      let playIndex = e.currentTarget.dataset.index;
      this.setData({
          playIndex:playIndex
      },()=>{
          this.getMusicMsg();
      })
  },
  // 获取当前音乐的播放地址；
  async getPlayUrl(){
      let res = await getMusicUrl(this.data.musicMsg.id);
      console.log(res)
      let playUrl = res.data.data[0].url;
      if(!playUrl){
          wx.showToast({
            title: '抱歉！vip歌曲暂不能播放',
            icon:"none"
          })
          //自动播放下一曲
          this.nextMusic()
          return
      }
      this.getBackgroundAudioManager(playUrl);
  },
  // 获取音频管理器
  getBackgroundAudioManager(playUrl){
      this.BackgroundAudioManager=wx.getBackgroundAudioManager();
       console.log(this.BackgroundAudioManager)
      //  设置播放路径
       this.BackgroundAudioManager.src = playUrl;
      // 设置播放标题
       this.BackgroundAudioManager.title=this.data.musicMsg.name;
       this.BackgroundAudioManager.singer = this.data.musicMsg.ar;
       this.BackgroundAudioManager.coverImgUrl=this.data.musicMsg.picUrl;
      //  监听音频播放事件
      this.BackgroundAudioManager.onPlay(()=>{
          console.log("开始播放拉")
          this.setData({
              playSate:true
          })
      })
      // 监听音频暂停事件
      this.BackgroundAudioManager.onPause(()=>{
          this.setData({
              playSate:false
          })
      }),
      //监听音频自动播放结束
      this.BackgroundAudioManager.onEnded(()=>{
        if(this.data.playIndex == 0){
          //随机播放
          this.randomMusic();
        }else if(this.data.playMode == 1){
          //顺序播放
          this.nextMusic();

        }else{
          //单曲循环
          this.getMusicMsg()
        }
      }),
      //监听歌曲可以正常播放
      this.BackgroundAudioManager.onCanplay(()=>{
        // console.log("可以正常播放了")
        // console.log()
        // 获取当前播放市场
        // console.log(duration)
        wx.nextTick(()=>{
            let duration = this.BackgroundAudioManager.duration;
            console.log(duration)
            this.getmusicTime(duration);
            this.getmusicTime(duration).then((res)=>{
              console.log(res)
              this.setData({
                duration:res
              })
            })

        })

      }),
      //监听音频更新事件
      this.BackgroundAudioManager.onTimeUpdate(()=>{
        let currentTime = this.BackgroundAudioManager.currentTime;        
        console.log(currentTime);
        //计算当前播放进度所占市场百分比
        let duration = this.BackgroundAudioManager.duration;
        let percent = currentTime / duration * 100;
        this.getmusicTime(currentTime).then(res=>{
          console.log(res);
          this.setData({
            currentTime:res,
            percent:percent
          })
        })

      })





  },
  //下一曲
  nextMusic(){
    this.data.playIndex ++
    if(this.data.playIndex>this.data.playList.length-1){
        this.data.playIndex = 0;
    }
    this.setData({
      playIndex:this.data.playIndex
    },()=>{
      this.getMusicMsg()
    })
  },
  //上一曲
  preMusic(){
    this.data.playIndex -- ;
    // 判断当前歌曲是否在第一曲
    if(this.data.playIndex<0){
        this.data.playIndex = this.data.playList.length-1;
    }
    this.setData({
        playIndex:this.data.playIndex
    },()=>{
        this.getMusicMsg();
    })
},
  //随机播放
  randomMusic(){
    // 随机生成播放索引
    let playIndex = Math.floor(Math.random()*this.data.playList.length);
    this.setData({
        playIndex
    },()=>{
        this.getMusicMsg();
    })
},

//
  getmusicTime(time){
    return new Promise((resolve,reject)=>{
      console.log(time)
      time = Math.round(time);
      let m = Math.floor(time/60);
      let s = time % 60;
      m = m<10?'0'+m:m;
      s = s<10?'0'+s:s;
      resolve(m+":"+s)
    })
  },

  //快进快退
  getSeek(e){
    let percent = e.detail / 100;
    // 根据百分比计算当前播放进度
    let seek = percent * this.BackgroundAudioManager.duration;
    console.log(seek)
    this.BackgroundAudioManager.seek(seek);
},
})